<template>
  <!-- 菜单配置  -->
  <div class="menu-page">
    <div id="menu-config">
      <div id="menu-config-table">
        <el-table
            :data="menuData"
            style="width: 100%; margin-bottom: 20px"
            row-key="empty.id"
            :expand-row-keys="exp"
            @expand-change="expChange"
            :tree-props="{ children: 'children'}"
            highlight-current-row
            @row-click="rowClick"
            @cell-click="cellClick"
            ref="menuTableRef"
        >
          <el-table-column label="菜单名">
            <template #default="scope">
              <el-icon>
                <component :is="scope.row.empty.icon"/>
              </el-icon>
              {{ scope.row.empty.title }}
            </template>
          </el-table-column>
          <el-table-column prop="empty.status" label="状态" width="100px">
            <template #default="ctx">
              <el-switch v-model="ctx.row.empty.status"
                         @click.stop
                         @change="modifyStatus(ctx.row)"
                         active-text="启用"
                         inactive-text="禁用"
                         inline-prompt
              />
            </template>
          </el-table-column>
          <el-table-column label="路径">
            <template #default="scope">
              <span class="menu-path">{{ scope.row.empty.path ===''?'group':scope.row.empty.path }}</span>
<!--              {{ scope.row.empty.path }}-->
            </template>
          </el-table-column>
          <el-table-column prop="empty.component" label="组件" width="500px">
            <template #default="scope">
              <span class="menu-comp">{{ scope.row.empty.component ===''?'nil':scope.row.empty.component }}</span>
              <!--              {{ scope.row.empty.path }}-->
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200px">
            <template #default="ctx">
              <el-button icon="Plus" link @click="OpenAdd(ctx.row)" type="primary"/>
              <el-button icon="Edit" link type="warning"/>
              <el-popconfirm :title="'你确定要删除 \''+ctx.row.empty.name+'\' 菜单项吗?'"
                             @confirm="confirmEvent(ctx.row)"
                             @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button icon="Delete" link type="danger"/>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button link type="primary" style="width: 100%;margin-bottom: 10px" @click="OpenAdd(null)">添加菜单
        </el-button>
      </div>
    </div>
    <el-dialog
        v-model="addflag"
        width="30%"
        append-to-body
        draggable
        title="添加菜单项"
        style="border-radius: 10px"
    >
      <el-form
          label-width="100px"
          :model="menuInfo"
          style="max-width: 460px"
      >
        <el-form-item label="类型">
          <el-select
              v-model="menuInfo.type"
              value-key="value"
              @change="selectType"
              placeholder="类型"
          >
            <el-option v-for="v in mt" :label="v.label" :value="v" :key="v.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称">
          <el-input v-model="menuInfo.title" placeholder="菜单名称"/>
        </el-form-item>
        <el-form-item label="菜单路径">
          <el-input v-model="menuInfo.path" placeholder="路由路径" :disabled="!ismenu"/>
        </el-form-item>
        <el-form-item label="路由名称">
          <el-input v-model="menuInfo.name" placeholder="路由名" :disabled="!ismenu"/>
        </el-form-item>
        <el-form-item label="组件">
          <el-input v-model="menuInfo.component" placeholder="组件路径" :disabled="!ismenu"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="Add">添加</el-button>
        <el-button @click="addflag=!addflag">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";
import Axios from "../../../plugins/axios";
import {ElMessage} from "element-plus";
import {sys} from "../../../model/system";
import event from "../../../plugins/event";
import {UpdateMenu} from "../../../plugins/evenKey";

const exp = ref<number[]>([])       // 记录表格展开的 id属性
const menuData = ref<any>([])       // 表格数据
const addflag = ref(false)          // 打开添加对话框标识符
const CurrentRow = ref<any>(null)   //记录当前操作行
const menuTableRef = ref()                 // 表格引用

function expChange(row) {
  let index = exp.value.indexOf(row.empty.id)
  if (index != -1) {
    exp.value.splice(index, 1)
  } else {
    exp.value.push(row.empty.id)
  }
}

function rowClick(row, column, event) {
  CurrentRow.value=row
  let index = exp.value.indexOf(row.empty.id)
  if (index != -1) {
    exp.value.splice(index, 1)
    menuTableRef.value.toggleRowExpansion(row, false)
  } else {
    exp.value.push(row.empty.id)
    menuTableRef.value.toggleRowExpansion(row, true)
  }
}

function cellClick(row, column, cell, event) {
  CurrentRow.value=row
  console.log(0)
  if (column.property==="empty.status"){
    return
  }
  let index = exp.value.indexOf(row.empty.id)
  if (index != -1) {
    exp.value.splice(index, 1)
    menuTableRef.value.toggleRowExpansion(row, false)
  } else {
    exp.value.push(row.empty.id)
    menuTableRef.value.toggleRowExpansion(row, true)
  }
}

// menuInfo 添加菜单表单信息
const menuInfo = ref({
  title: '', // 标题
  name: '',// 路由名称
  component: '',//组件信息
  path: '',// 菜单路由路径 此处的菜单管理基于 菜单工具蓝 /index/ 开头的路径
  type: {
    label: '',
    value: 0
  }, // 菜单类型 可选类型是 分组 或者 菜单项
  icon: '', // 菜单图标选择
  status: false
})

// 菜单类型
const mt = [
  {label: '分组', value: 0},
  {label: '页面', value: 1}
]

// menuOld 记录 切换类型的中间变量
const menuOld = ref()

// 标识当前 添加的菜单项 是否是页面具体菜单
const ismenu = ref(false)

// 切换添加的菜单类型，记录对应的编辑状态
function selectType(data) {
  ismenu.value = true
  if (data.value == 0) {
    ismenu.value = false
    menuOld.value = {...menuInfo.value}
    menuInfo.value.name = ''
    menuInfo.value.component = ''
  } else {
    if (menuOld.value != null) {
      menuInfo.value = {...menuOld.value}
      menuInfo.value.type = data
    }
  }
}

// 打开添加窗口
function OpenAdd(row) {
  menuInfo.value = {
    title: '', // 标题
    name: '',// 路由名称
    component: '',//组件信息
    path: '',// 菜单路由路径 此处的菜单管理基于 菜单工具蓝 /index/ 开头的路径
    type: {
      label: '',
      value: 0
    }, // 菜单类型 可选类型是 分组 或者 菜单项
    icon: '', // 菜单图标选择
    status: false
  }
  addflag.value = !addflag.value
  ismenu.value = false
  CurrentRow.value = row
}

// 执行添加
function Add() {
  let pid = 0
  let name = menuInfo.value.name
  let path = menuInfo.value.path
  let row = CurrentRow.value
  if (row !== null) {
    pid = row.empty.id
  }
  console.log(menuInfo.value)
  Axios.post('/api/configuration/menu/add', {
    pid: pid,
    name: name,
    path: path,
    title: menuInfo.value.title,
    status: menuInfo.value.status,
    component: menuInfo.value.component
  }).then(response => {
    let data = response.data
    if (data.code === "0000") {
      ElMessage({
        type: 'success',
        message: '添加成功',
        duration: 1000
      })
      init()
      event.emit(UpdateMenu)
    }
  })
  addflag.value = !addflag.value
  CurrentRow.value = null
}

const confirmEvent = (row) => {
  if (row.children.length !== 0) {
    ElMessage({
      type: 'warning',
      message: row.empty.title + ' 存在子菜单，请先删除子菜单'
    })
    return
  }
  Axios.post('/api/configuration/menu/del', {
    id: row.empty.id
  }).then(respone => {
    let data = respone.data
    if (data.code === "0000") {
      ElMessage({
        type: 'success',
        message: row.empty.title + ' 删除成功'
      })
      init()
      event.emit(UpdateMenu)
    }
  })
}
const cancelEvent = () => {
  console.log('cancel!')
}


// 状态修改 ，强制限制不能禁用系统配置及其子配置项  row.empty.pid === 9 来源于数据库初始化 id
function modifyStatus(row) {
  if (row!==null){
    if (row.empty.title === "系统配置" || row.empty.pid === 9) {
      ElMessage({
        type: 'warning',
        message: '系统配置禁止操作'
      })
      init()
      return
    }
  }
  Axios.post('/api/configuration/menu/status', {
    pid: row.empty.id,
    status: row.empty.status
  }).then(response => {
    let data: sys.Result<any> = response.data
    if (data.code === '0000') {
      if (data.msg !== '') {
        ElMessage({
          type: 'success',
          message: data.msg
        })
      }
      init()
      event.emit(UpdateMenu)
    }
  })
}

function init() {
  Axios.get('/api/configuration/menu/tree?pid=0').then(rep => {
    let data = rep.data
    if (data.code === "0000") {
      menuData.value = data.data
    }
  })
}

onMounted(init)

</script>

<style scoped>
#menu-config {
  width: 100%;
  display: flex;
  flex-direction: column;
}

#menu-config-table {
  width: 97%;
  margin: auto;
  height: 700px;
  background-color: white;
  box-shadow: var(--el-box-shadow-light);
}
.menu-path{
  background-color: rgba(218, 205, 205, 0.92);
  border-radius: 10px;
  color: #ffffff;
  padding: 5px;
}
.menu-comp{
  background-color: rgb(65, 208, 28);
  border-radius: 10px;
  color: #ffffff;
  padding: 5px;
}
</style>